<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryFormRef" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable style="width: 200px" @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="评分" prop="rating">
        <el-select v-model="queryParams.rating" placeholder="请选择评分" clearable>
          <el-option v-for="item in ratingOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['order:review:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['order:review:edit']" type="success" plain icon="Edit" :disabled="single" @click="() => handleUpdate()"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['order:review:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="() => handleDelete()"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['order:review:audit']" type="warning" plain icon="Check" @click="handleAuditPage">评价审核</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="商品信息" align="center" min-width="300">
        <template #default="scope">
          <div v-for="item in scope.row.orderDetail" :key="item.id" class="product-info">
            <el-image :src="item.productImage" :preview-src-list="[item.productImage]" fit="cover" class="product-image" />
            <div class="product-detail">
              <div class="product-name">{{ item.productName }}</div>
              <div v-if="item.specs" class="product-specs">
                <el-tag size="small" type="info">{{ item.specs }}</el-tag>
              </div>
              <div class="product-price">
                <span class="price">¥{{ item.price }}</span>
                <span class="quantity">x{{ item.quantity }}</span>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="评分" align="center" prop="rating" width="180">
        <template #default="scope">
          <el-rate v-model="scope.row.rating" disabled show-score text-color="#ff9900" score-template="{value}星" />
        </template>
      </el-table-column>
      <el-table-column label="评价内容" align="center" prop="content" :show-overflow-tooltip="true" min-width="200">
        <template #default="scope">
          <div class="review-content">
            <div class="content-text">{{ scope.row.content }}</div>
            <div class="content-actions">
              <el-button link type="primary" @click="handleViewDetail(scope.row)">查看详情</el-button>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="评价图片" align="center" width="120">
        <template #default="scope">
          <div v-if="scope.row.images" class="review-images">
            <el-image :src="scope.row.images.split(',')[0]" :preview-src-list="scope.row.images.split(',')" fit="cover" class="review-image" />
            <span v-if="scope.row.images.split(',').length > 1" class="image-count"> +{{ scope.row.images.split(',').length - 1 }} </span>
          </div>
          <span v-else>无图片</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="getStatusTag(scope.row.status) as 'success' | 'warning' | 'info' | 'danger'">
            {{ getStatusLabel(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button v-hasPermi="['order:review:edit']" link type="primary" icon="Edit" @click="() => handleUpdate(scope.row)">修改</el-button>
          <el-button v-hasPermi="['order:review:remove']" link type="primary" icon="Delete" @click="() => handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

    <!-- 添加或修改订单评价对话框 -->
    <el-dialog v-model="open" :title="title" width="500px" append-to-body>
      <el-form ref="reviewFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单编号" prop="orderId">
          <el-input v-model="form.orderNo" placeholder="请输入订单编号" />
        </el-form-item>
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="form.rating" :texts="['很差', '较差', '一般', '不错', '很好']" show-text />
        </el-form-item>
        <el-form-item label="评价内容" prop="content">
          <el-input v-model="form.content" type="textarea" placeholder="请输入评价内容" />
        </el-form-item>
        <el-form-item label="评价图片" prop="images">
          <image-upload v-model="form.images" :is-show-tip="false" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailOpen" title="评价详情" width="600px" append-to-body>
      <div class="review-detail">
        <div class="review-header">
          <div class="order-info">
            <span class="label">订单编号：</span>
            <span>{{ detailData.orderNo }}</span>
          </div>
          <div class="review-time">
            <span class="label">评价时间：</span>
            <span>{{ parseTime(detailData.createTime) }}</span>
          </div>
        </div>
        <div class="review-rating">
          <span class="label">评分：</span>
          <el-rate v-model="detailData.rating" disabled show-score text-color="#ff9900" score-template="{value}星" />
        </div>
        <div class="review-content">
          <span class="label">评价内容：</span>
          <div class="content-text">{{ detailData.content }}</div>
        </div>
        <div v-if="detailData.images" class="review-images">
          <span class="label">评价图片：</span>
          <div class="image-list">
            <el-image
              v-for="(img, index) in detailData.images.split(',')"
              :key="index"
              :src="img"
              :preview-src-list="detailData.images.split(',')"
              fit="cover"
              class="detail-image"
            />
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="auditOpen" :title="auditTitle" width="500px" append-to-body>
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="80px">
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitAudit">确 定</el-button>
          <el-button @click="cancelAudit">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { OrderReviewVO, OrderReviewQuery, OrderReviewForm } from '@/api/order/review/types';
import { listOrderReview, getOrderReview, addOrderReview, updateOrderReview, delOrderReview } from '@/api/order/review';
import { parseTime } from '@/utils/ruoyi';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';

const router = useRouter();

// 评分选项
const ratingOptions = [
  { value: 1, label: '1星' },
  { value: 2, label: '2星' },
  { value: 3, label: '3星' },
  { value: 4, label: '4星' },
  { value: 5, label: '5星' }
];

// 状态选项
const statusOptions = [
  { value: 0, label: '待审核' },
  { value: 1, label: '已通过' },
  { value: 2, label: '已拒绝' }
];

// 获取状态标签
const getStatusLabel = (value: number) => {
  return statusOptions.find((item) => item.value === value)?.label || '未知';
};

// 获取状态标签样式
const getStatusTag = (value: number) => {
  const map: Record<number, string> = {
    0: 'info',
    1: 'success',
    2: 'danger'
  };
  return map[value] || 'info';
};

const loading = ref(true); // 遮罩层
const ids = ref<number[]>([]); // 选中数组
const single = ref(true); // 非单个禁用
const multiple = ref(true); // 非多个禁用
const showSearch = ref(true); // 显示搜索条件
const total = ref(0); // 总条数
const list = ref<OrderReviewVO[]>([]); // 列表数据
const title = ref(''); // 弹出层标题
const open = ref(false); // 是否显示弹出层
const detailOpen = ref(false);
const detailData = ref<OrderReviewVO>({});

const queryParams = ref<OrderReviewQuery>({
  pageNum: 1,
  pageSize: 10
});

const form = ref<OrderReviewVO>({});
const rules = ref({
  orderId: [{ required: true, message: '订单编号不能为空', trigger: 'blur' }],
  rating: [{ required: true, message: '评分不能为空', trigger: 'change' }],
  content: [{ required: true, message: '评价内容不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
});

const auditOpen = ref(false);
const auditTitle = ref('');
const auditForm = ref({
  id: undefined,
  status: 1
});

const auditRules = ref({
  status: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
});

/** 查询订单评价列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listOrderReview(queryParams.value);
    console.log(res);
    list.value = res.rows;
    total.value = res.total;
  } finally {
    loading.value = false;
  }
};

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  reset();
};

/** 表单重置 */
const reset = () => {
  form.value = {};
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10
  };
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderReviewVO[]) => {
  ids.value = selection.map((item) => item.id!);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = '添加订单评价';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: OrderReviewVO) => {
  reset();
  const id = row?.id || ids.value[0];
  const res = await getOrderReview(id);
  console.log(res);
  form.value.id = res.data.id;
  form.value.orderId = res.data.orderId;
  form.value.orderNo = res.data.orderNo;
  form.value.userId = res.data.userId;
  form.value.rating = res.data.rating;
  form.value.content = res.data.content;
  form.value.images = res.data.images;
  form.value.status = res.data.status;
  // form.value = res.data;
  open.value = true;
  title.value = '修改订单评价';
};

/** 提交按钮 */
const submitForm = async () => {
  // const reviewFormRef = ref();
  // await reviewFormRef.value.validate();

  if (form.value.id) {
    await updateOrderReview(form.value as OrderReviewForm);
    ElMessage.success('修改成功');
  } else {
    await addOrderReview(form.value as OrderReviewForm);
    ElMessage.success('新增成功');
  }
  open.value = false;
  getList();
};

/** 删除按钮操作 */
const handleDelete = async (row?: OrderReviewVO) => {
  const reviewIds = row?.id ? [row.id] : ids.value;
  await ElMessageBox.confirm('是否确认删除订单评价编号为"' + reviewIds + '"的数据项?');
  await delOrderReview(reviewIds);
  getList();
  ElMessage.success('删除成功');
};

/** 上传成功回调 */
const handleUploadSuccess = (response: any) => {
  if (response.code === 200) {
    form.value.images = response.data;
  } else {
    ElMessage.error('上传失败');
  }
};

/** 移除图片回调 */
const handleUploadRemove = () => {
  form.value.images = '';
};

/** 查看详情按钮操作 */
const handleViewDetail = (row: OrderReviewVO) => {
  detailData.value = row;
  detailOpen.value = true;
};

/** 审核按钮操作 */
const handleAudit = (row: OrderReviewVO, status: number) => {
  auditForm.value = {
    id: row.id,
    status: status
  };
  auditTitle.value = status === 1 ? '审核通过' : '审核拒绝';
  auditOpen.value = true;
};

/** 取消审核 */
const cancelAudit = () => {
  auditOpen.value = false;
  auditForm.value = {
    id: undefined,
    status: 1
  };
};

/** 提交审核 */
const submitAudit = async () => {
  const auditFormRef = ref();
  await auditFormRef.value.validate();
  try {
    await updateOrderReview({
      id: auditForm.value.id,
      status: auditForm.value.status
    } as OrderReviewForm);
    ElMessage.success('审核成功');
    auditOpen.value = false;
    getList();
  } catch (error) {
    console.error('审核失败:', error);
    ElMessage.error('审核失败');
  }
};

/** 跳转到审核页面 */
const handleAuditPage = () => {
  router.push('/order/review-audit/index');
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.product-info {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  padding: 12px;
  border-radius: 8px;
  background-color: #f5f7fa;
  transition: all 0.3s;
}

.product-info:hover {
  background-color: #ecf5ff;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 16px;
  border-radius: 6px;
  object-fit: cover;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.product-detail {
  flex: 1;
  text-align: left;
}

.product-name {
  font-size: 15px;
  color: #303133;
  margin-bottom: 8px;
  font-weight: 500;
}

.product-specs {
  margin-bottom: 8px;
}

.product-price {
  font-size: 14px;
  color: #606266;
}

.product-price .price {
  color: #f56c6c;
  font-weight: 500;
  margin-right: 12px;
}

.product-price .quantity {
  color: #909399;
}

.review-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 8px;
}

.content-text {
  text-align: left;
  line-height: 1.5;
  word-break: break-all;
}

.content-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 4px;
  border-top: 1px dashed #ebeef5;
  padding-top: 8px;
}

.review-images {
  position: relative;
  display: inline-block;
}

.review-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}

.image-count {
  position: absolute;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  padding: 2px 6px;
  border-radius: 0 0 4px 0;
  font-size: 12px;
}

.review-detail {
  padding: 20px;
}

.review-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.review-rating {
  margin-bottom: 20px;
}

.review-content {
  margin-bottom: 20px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.detail-image {
  width: 120px;
  height: 120px;
  border-radius: 4px;
  object-fit: cover;
}

.label {
  color: #606266;
  font-weight: 500;
  margin-right: 8px;
}
</style>
